import React, { Component } from 'react';
import { Card, Upload, Spin } from 'antd';
import { connect } from 'react-redux';
import { changeAvatar } from '../../actions/user';
import axios from 'axios';
const mapStateToProps = state => ({
  avatar: state.User.avatar
});
@connect(mapStateToProps, { changeAvatar })
class Profile extends Component {
  state = {
    isLoading: false
  };
  handleUploadImg = ({ file }) => {
    this.setState({
      isLoading: true
    });
    const data = new FormData();
    data.append(
      'Token',
      '23a3a3390ed01a1e2ed371d45685b1faa6b7920f:Qn_h0eb1uJ4siT15ebdOZMh1I6Y=:eyJkZWFkbGluZSI6MTU4MTY5MTk4MywiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzA5NjYxIiwiYWlkIjoiMTY2Mzc4NSIsImZyb20iOiJmaWxlIn0='
    );
    data.append('file', file);
    axios
      .post('http://up.imgapi.com/', data)
      .then(res => {
        if (res.status === 200) {
          //将url存到redux里面，上传的时候同步将header里面的头像也改变
          //处理错误
          this.setState({
            isLoading: false
          });
          this.props.changeAvatar(res.data.linkurl);
        } else {
          //处理错误
        }
      })
      .catch(() => {
        //处理错误
      });
  };
  render() {
    console.log(this.props.avatar);
    return (
      <Card title="个人设置" bordered={false}>
        {/* showUploadList：不会显示上传的文件列表 */}
        <Upload showUploadList={false} customRequest={this.handleUploadImg}>
          <Spin spinning={this.state.isLoading}>
            <div
              style={{
                width: 100,
                height: 100,
                border: '1px dashed #dedede',
                textAlign: 'center',
                lineHeight: '100px'
              }}
            >
              <img
                src={this.props.avatar}
                alt=""
                style={{ display: 'block', width: 98, height: 98 }}
              />
            </div>
          </Spin>
        </Upload>
      </Card>
    );
  }
}
export default Profile;
